package filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {
    private static String[] paths;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String initParameter = filterConfig.getInitParameter("letgo");
        paths =initParameter.split(";");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String path = request.getServletPath();

        for (int i = 0; i < paths.length; i++) {
            if (path.startsWith(paths[i])) {
                chain.doFilter(request, response);
                return;
            }
        }
        String name = (String) request.getSession().getAttribute("name");
//        System.out.println(path);
//        System.out.println(name);


        if (name == null || "".equals(name) || name.length() == 0) {
//            request.getSession().setAttribute("error", "尚未登录，请登录");
            request.setAttribute("result", "登陆之后才可以访问其他网站！");
            response.sendRedirect("/");
//            request.getRequestDispatcher("/").forward(request,response);
            return;

        }
        //剩下的情况为已登录，放行
        chain.doFilter(request, response);
    }



    @Override
    public void destroy() {

    }
}